//
// Created by Snow on 2023/3/7.
//
#include<cstdio>
#include<cstdlib>
typedef int ElemType;
#define MaxCol 10//最大列数
typedef struct Node1//定义数据结点类型
{
    ElemType data[MaxCol];//存放一行的数据
    struct Node1 *next;//指向后继数据结点
}DList;//行结点类型
typedef struct Node2
{
    int Row,Col;//行数和列数
    DList *next;//指向第一个数据结点
}HList;//头结点类型
void CreateTable(HList *&h)
{
    int i,j;
    DList *r,*s;
    h=(HList *)malloc(sizeof(HList));
    printf("Please enter the Row and Col:");
    scanf_s("%d%d",&h->Row,&h->Col);
    h->next= nullptr;
    for(i=0;i<h->Row;i++) {
        printf("Line %d:", i + 1);
        s = (DList *) malloc(sizeof(DList));
        for (j = 0; j < h->Col; j++)
            scanf_s("%d", &s->data[j]);
        if (h->next == nullptr)
            h->next = s;
        else
            r->next = s;
        r = s;
    }
    r->next=nullptr;
}
void DestroyList(HList *&h)
{
    DList *pre=h->next,*p=pre->next;
    while(p!=nullptr)
    {
        free(pre);
        pre=p;
        p=p->next;
    }
    free(pre);
    free(h);
}
void DispList(HList *h)
{
    int j;
    DList *p=h->next;
    while(p!=nullptr)
    {
        for(j=0;j<h->Col;j++)
            printf("%4d ",p->data[j]);
        printf("\n");
        p=p->next;
    }
}
void LinkTable(HList *h1,HList *h2,HList *&h)
{
    int i,j,k;
    DList *p=h1->next,*q,*s,*r;
    printf("The connection fields are: the first table number and the second table number:");
    scanf_s("%d%d",&i,&j);
    h=(HList *)malloc(sizeof(HList));
    h->Row=0;
    h->Col=h1->Col+h2->Col;
    h->next=nullptr;
    while(p!=nullptr)
    {
        q=h2->next;
        while(q!=nullptr)
        {
            if(p->data[i-1]==q->data[j-1])
            {
                s=(DList *)malloc(sizeof(DList));
                for(k=0;k<h1->Col;k++)
                    s->data[k]=p->data[k];
                for(k=0;k<h2->Col;k++)
                    s->data[h1->Col+k]=q->data[k];
                if(h->next==nullptr)
                    h->next=s;
                else
                    r->next=s;
                r=s;
                h->Row++;
            }
            q=q->next;
        }
        p=p->next;
    }
    r->next=nullptr;
}
int main()
{
    HList *h1,*h2,*h;
    printf("Table 1:\n");
    CreateTable(h1);
    printf("Table 2:\n");
    CreateTable(h2);
    LinkTable(h1,h2,h);
    printf("Connection result table:\n");
    DispList(h);
    DestroyList(h1);
    DestroyList(h2);
    DestroyList(h);
    return 0;
}